// pages/book-return/book-return.js
var util = require('../../../utils/util.js');
var api = require('../../../config/api.js');
var app = getApp();
Page({
  data: {
    codeShow: false,
    progress: true,
    title: "加载中",
    borrowId: 0,
    errorMsg: "",
    redit: 80,
    timer:'',
  },
  onLoad: function (options) {
    var that = this;
    var borrowId = options.borrowId;
    var user = wx.getStorageSync("user");
    var user1 = app.globalData.user;
    var day = options.day;

    var userCredit = wx.getStorageSync("user").credit;
    this.setData({ 
      credit: userCredit ,
      borrowId: borrowId
    });
    /*util.request(api.returnBook,{bookId:bookId}).then(function(res){
      that.setData({ borrowId: res.data });
    });*/
    var that = this;
    setTimeout(function () {
      that.setData({
        codeShow: true, progress: false, title: "请向管理员出示下方的还书码",
        errorMsg: "还书错误！"
      });
      that.data.timer = setInterval(function () {
        util.request(api.getBorrow,{borrowId:that.data.borrowId}).then(function(res){
          if (res.data.borrow.status == 2) {
            clearTimeout(that.data.timer);
            /*wx.showToast({
              title: '还书成功',
              icon: 'success',
              duration: 2000
            })*/
            //clearInterval(that.data.timer);
            console.log("delayDay:" + res.data.borrow.delayDay);
            console.log("borrow:" + res.data.borrow);
            console.log("status:" + res.data.borrow.status);
            if(res.data.borrow.delayDay!=0){  //逾期
              var day = res.data.borrow.delayDay;
              var money = day;
              wx.showModal({
                title: '还书成功',
                content: '该图书逾期' + day + '天，将以1元/天扣费情况进行扣费，总共扣费：' + day + '元',
                success: function (res) {
                  if (res.confirm) {
                    util.request(api.IndexRootUrl + 'user/updateMoney', { money:money })
                      .then(function (res) {
                        console.log(res);
                      });
                    wx.navigateTo({
                      url: '/pages/ucenter/book-return-list/book-return-list',
                    });
                  } else if (res.cancel){
                    util.request(api.IndexRootUrl + 'borrow/updateStatus', { borrowId: res.data.borrow.id, status: 1 })
                      .then(function (res) {
                        console.log(res);
                      });
                  }
                }
              })
            }else{
              wx.showToast({
                title: '还书成功',
                icon: 'success',
                duration: 2000
              });
              wx.navigateTo({
                url: '/pages/ucenter/book-return-list/book-return-list',
              });
            }
          }
        });
      }, 1000)
    }, 4000)
  },

  onUnload:function(){
    let that = this;
    clearInterval(that.data.timer)
  },

})